import { debounce, get, omit } from "lodash-es";
import { isArray, isBoolean, isFunction, isObject, isFormValue } from "@/utils";
import { DynamicTableEmitFn, DynamicTableProps } from "../dynamic-table";
import { OnChangeCallbackParams } from "../types";
import { TableColumn } from "../types/column";
import { Pagination, TableState } from "./useTableState";
import { useSystemStore } from "@/store/login";
import { copyToClipboard } from "@/utils/tools";
import {
  getAppId
} from '@/utils/core'

export type TableMethods = ReturnType<typeof useTableMethods>;
export type UseTableMethodsContext = {
  state: TableState;
  props: DynamicTableProps;
  emit: DynamicTableEmitFn;
};
// const retryFetchCount = 2;
export const useTableMethods = ({
  state,
  props,
  emit,
}: UseTableMethodsContext) => {
  const getCheckData = (data: any) => {
    return state.tableRef.value?.getCheckData();
  };
  // 获取表格列key
  const getColumnKey = (column: TableColumn) => {
    return (column?.key || "id") as string;
  };
  const { innerPropsRef, tableData, loadingRef, page, defaultPagination } =
    state;
  const setProps = (props: Partial<DynamicTableProps>) => {
    innerPropsRef.value = { ...unref(innerPropsRef), ...props };
  };
  /**
   * @description 表格查询
   */
  const handleSubmit = (params: any, page = 1) => {
    params.page = page;
    fetchData(params);
  };

  // format request searchParam value
  const formatValue = (value, type) => {
    // 渲染日期组件但类型为整数
    if (["41", "42"].includes(type.disType || type.eleDisType)) {
      return value?.replace("-", "");
    }
    // 排除输入框范围
    if (isArray(value) && value.every((v) => v === "")) {
      return null;
    }
    if (isArray(value)) {
      return value.join(",");
    }
    if (isBoolean(value)) {
      return Number(value);
    }
    return value;
  };

  const handleFilterQuery = (query) => {
    return Object.keys(query).filter(
      (q) => !q.includes("cm_") || q === "isChild",
    );
  };

  /**
   * @param {object} params 表格查询参数
   * @param {boolean} flush 是否将页数重置到第一页
   * @description 获取表格数据
   */
  const fetchData: any = debounce(async (params = {}) => {
    const { dataRequest, dataSource, queryFormRef } = props as any;
    const { tableRef } = state;
    if (!dataRequest || !isFunction(dataRequest)) {
      return;
    }
    try {
      let pageParams: Recordable = {};
      const pagination = unref(page)!;
      // 是否启用了分页
      const enablePagination = isObject(pagination);
      if (enablePagination) {
        pageParams = {
          PageIndex: pagination.current,
          PageSize: pagination.limit,
        };
      }
      // 表格查询参数
      const queryParams: Recordable = {
        ...pageParams,
        ...params,
      };
      await nextTick();
      // 当tag_table组件中 包含多个tab-item时，queryFormRef可能为array
      // 此处做兼容处理

      const formatFormRef = isArray(queryFormRef)
        ? queryFormRef[0]
        : queryFormRef;

      let searchParam = {};

      if (formatFormRef) {
        const values = await formatFormRef?.validate();
        searchParam = values.model;

        // queryParams = {
        //   // ...values.model,
        //   ...queryParams,
        // };
      }

      loadingRef.value = true;
      // const searchParam = omit(queryParams, [
      //   "PageIndex",
      //   "PageSize",
      //   "current",
      //   "limit",
      //   "isTrusted",
      //   "_vts",
      // ]);

      // format searchParam params
      const searchParamArr: any[] = [];
      for (const key in searchParam) {
        if (Object.prototype.hasOwnProperty.call(searchParam, key)) {
          const type = props.schema[key] as any;
          // if (key.indexOf("-copyText") > -1) {
          // } else {

          if (!key.includes("-copyText")) {
            const value = formatValue(searchParam[key], type);

            isFormValue(value) &&
              searchParamArr.push({
                columnCode: key,
                filterType: type?.filterType || 1,
                // 当组件value为array时，转为以,分割的string
                value,
              });
          }

          // }
        }
      }
      // const userInfoStore = useSystemStore();

      // get request params
      const paramsnew = {
        clientMacro: JSON.stringify({
          treeKey: props.treeKey,
          treeName: props.treeName,
          appId: getAppId(),
          ...omit(props.query, handleFilterQuery(props.query)),
        }),
        pageId: props.pageId,
        queryParam: JSON.stringify(queryParams),
        searchParam: JSON.stringify(searchParamArr),
      };
      localStorage.setItem("paramsnew", JSON.stringify(paramsnew));
      // run request
      const res = (await dataRequest(paramsnew)).data;
      const isArrayResult = Array.isArray(res);
      const resultItems: Recordable[] = isArrayResult ? res : get(res, "data");

      // 执行props.callback 回调
      if (
        props.callback &&
        props.callback.beforeBinded &&
        isFunction(props.callback.beforeBinded)
      ) {
        props.callback.beforeBinded(resultItems, tableRef);
      }

      const resultTotal: number = isArrayResult
        ? res.length
        : Number(get(res, "totalCount"));

      const columns = res.tableInfo.fieldList
        .filter((_) => _.accessRight >= 2)
        .map((_: any) => {
          return {
            ..._,
            key: _.code,
            title: _.name,
          };
        });
      emit("update:columns", columns);
      // emit("update:columns", columns);

      if (enablePagination && resultTotal) {
        const {
          current = 1,
          limit = defaultPagination.value.limit,
          total = resultTotal,
        } = pagination;
        const currentTotalPage = Math.ceil(resultTotal / pagination.limit);
        if (current > currentTotalPage) {
          updatePagination({
            current: currentTotalPage,
          } as Pagination);
          return await fetchData(params);
        }
      }
      tableData.value = resultItems.map((_) => {
        return {
          ..._,
          ...(_.REFDATA || {}),
        };
      });
      updatePagination({ total: ~~resultTotal } as Pagination);
      if (queryParams.current) {
        updatePagination({ current: queryParams.current || 1 } as Pagination);
      }
      if (
        props.callback &&
        props.callback.onBinded &&
        isFunction(props.callback.onBinded)
      ) {
        props.callback.onBinded(resultItems, tableRef);
      }
      return tableData;
    } catch (error) {
      console.log(error, "request error");
      tableData.value = [];
      updatePagination({ total: 0 } as Pagination);
    } finally {
      setTimeout(() => {
        loadingRef.value = false;
      }, 500);
    }
  });
  /** 更新表格分页信息 */
  const updatePagination = (info: Pagination | undefined = page.value) => {
    if (isBoolean(info)) {
      page.value = info;
    } else if (isObject(page.value)) {
      page.value = {
        ...page.value,
        ...info,
      };
    }
  };
  const reload = (resetPageIndex = false) => {
    const pagination = unref(page);
    if (Object.is(resetPageIndex, true) && isObject(pagination)) {
      pagination.current = 1;
    }
    return fetchData();
  };
  const reset = async () => {
    const { queryFormRef } = props as any;

    const formatFormRef = isArray(queryFormRef)
      ? queryFormRef[0]
      : queryFormRef;

    if (formatFormRef) {
      await formatFormRef.resetFields();
      reload(true);
    }
  };
  /**
   * @description 分页改变
   */
  const handleTableChange = async (...rest: OnChangeCallbackParams) => {
    const [pagination] = rest;
    const { queryFormRef } = props as any;

    const formatFormRef = isArray(queryFormRef)
      ? queryFormRef[0]
      : queryFormRef;

    if (formatFormRef) {
      await formatFormRef.validate();
    }
    updatePagination(pagination as Pagination);
    await fetchData(pagination);
    emit("change", ...rest);
  };

  /**单元格双击*/
  const cellDouble = (val: string) => {
    copyToClipboard(val);
  };
  /**
   * 行单击
   */
  const rowClick = (row: object) => {
    const key = props.rowKey ?? "id";
    if (props.enableRadio) {
      state.selectedKey.value =
        state.selectedKey.value == row[key] ? "" : row[key];
    }
    if (props.enableCheckBox) {
      if (state.selectedKeys.value.includes(row[key])) {
        state.selectedKeys.value = state.selectedKeys.value.filter(
          (_) => _ != row[key],
        );
      } else {
        state.selectedKeys.value.push(row[key]);
      }
    }
  };
  /**
   * 排序
   */
  const sortChange = (key, sort) => {
    console.log(key, sort);
  };
  const handleEditFormValidate = () => {};

  return {
    reset,
    getColumnKey,
    setProps,
    fetchData,
    handleSubmit,
    reload,
    handleTableChange,
    handleEditFormValidate,
    getCheckData,
    cellDouble,
    formatValue,
    rowClick,
    sortChange,
  };
};
